/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.fresh.bus.canoe.xsocket;

import com.fresh.bus.canoe.message.MessageCodec;
import com.fresh.bus.canoe.message.Response;
import com.fresh.bus.canoe.session.support.AbstractSession;

import java.io.IOException;
import java.nio.ByteBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xsocket.connection.INonBlockingConnection;

/**
 *
 * @author panzd
 */
public class XSocketSession extends AbstractSession{
    private static final Logger log = LoggerFactory.getLogger(XSocketSession.class);

    private INonBlockingConnection connection;
    private MessageCodec messageCodec;

    public XSocketSession(INonBlockingConnection connection, MessageCodec messageCodec)
    {
        this.connection = connection;
        this.messageCodec = messageCodec;
    }

    /**
     * @return the connection
     */
    protected INonBlockingConnection getConnection() {
        return connection;
    }

    @Override
    public void send(Response response) {
        byte[] responseData = messageCodec.encodeResponse(response);

        ByteBuffer byteBuffer = ByteBuffer.allocate(responseData.length + 2);
        byteBuffer.putShort((short)responseData.length);
        byteBuffer.put(responseData);

        byteBuffer.flip();

        try
        {
        	//getConnection().setAutoflush(false);
        	getConnection().write(byteBuffer);
            getConnection().flush();
        }
        catch(IOException e)
        {
            log.error(e.getMessage());
        }
    }
}
